/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lucequestionhelper;

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;
import java.util.Vector;
import javax.swing.ImageIcon;

/**
 *
 * @author nabraham
 */
public class QuestionPanel extends javax.swing.JPanel {

    private Vector<String> _allQuestions;
    private Vector<String> _lowerCaseQuestions = new Vector<String>();
    private Vector<String> _possibleQuestions;
    private HashMap<String, Integer> _questionsAdded = new HashMap<String, Integer>();

    /**
     * Creates new form QuestionPanel
     */
    public QuestionPanel() {
        initComponents();
        initCustomComponents();
    }

    private void initCustomComponents() {
        statusLabel.setText("");
        datePicker.setDate(new Date());
        paintBanner();
    }

//    JPanel panel = ...
//    BufferedImage image = new BufferedImage(200, 200, TYPE_INT_ARGB);
//    Graphics2D gg = image.createGraphics();
//    try {
//        gg.translate(-100, -20);  // start point of region negated
//        panel.paint(gg);
//    } finally {
//        gg.dispose();
//    }
    private void paintBanner() {
        ImageIcon icon = new ImageIcon("data/banner.png");
        bannerButton.setIcon(icon);
        this.revalidate();
        this.repaint();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        possibleQuestionList = new javax.swing.JList();
        inputQuestionArea = new javax.swing.JTextField();
        addQuestionButton = new javax.swing.JButton();
        userDropdown = new javax.swing.JComboBox();
        exportButton = new javax.swing.JButton();
        quantityDropdown = new javax.swing.JComboBox();
        statusLabel = new javax.swing.JLabel();
        bannerButton = new javax.swing.JToggleButton();
        datePicker = new org.jdesktop.swingx.JXDatePicker();

        possibleQuestionList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Where is the bathroom?", "What time is it?" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        possibleQuestionList.setFixedCellWidth(140);
        possibleQuestionList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                possibleQuestionListMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(possibleQuestionList);

        inputQuestionArea.setText("<enter your question here>");
        inputQuestionArea.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                inputQuestionAreaActionPerformed(evt);
            }
        });
        inputQuestionArea.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                inputQuestionAreaKeyTyped(evt);
            }
            public void keyPressed(java.awt.event.KeyEvent evt) {
                inputQuestionAreaKeyPressed(evt);
            }
        });

        addQuestionButton.setText("Add Question");
        addQuestionButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addQuestionButtonActionPerformed(evt);
            }
        });

        userDropdown.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Mary", "Tierney", "Bridget", "James" }));

        exportButton.setText("Export All");
        exportButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exportButtonActionPerformed(evt);
            }
        });

        quantityDropdown.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" }));

        statusLabel.setText("status");
        statusLabel.setMinimumSize(new java.awt.Dimension(500, 16));

        bannerButton.setText("derp");

        datePicker.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                datePickerActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap(22, Short.MAX_VALUE)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(6, 6, 6)
                        .add(statusLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 745, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(bannerButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 730, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(inputQuestionArea, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 512, Short.MAX_VALUE)
                            .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 512, Short.MAX_VALUE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(userDropdown, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(layout.createSequentialGroup()
                                .add(addQuestionButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 118, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(exportButton))
                            .add(quantityDropdown, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(datePicker, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 217, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(bannerButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 100, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(inputQuestionArea, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(userDropdown, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(18, 18, 18)
                        .add(datePicker, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(178, 178, 178)
                        .add(quantityDropdown, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 50, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, addQuestionButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, exportButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 39, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .add(0, 0, Short.MAX_VALUE))
                    .add(layout.createSequentialGroup()
                        .add(9, 9, 9)
                        .add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)))
                .add(18, 18, 18)
                .add(statusLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void inputQuestionAreaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_inputQuestionAreaKeyTyped
    }//GEN-LAST:event_inputQuestionAreaKeyTyped

    private void possibleQuestionListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_possibleQuestionListMouseClicked
        if (evt.getClickCount() == 2) {
            int index = possibleQuestionList.locationToIndex(evt.getPoint());
            addQuestion(_possibleQuestions.get(index), 1);
        }
    }//GEN-LAST:event_possibleQuestionListMouseClicked

    private void addQuestionButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addQuestionButtonActionPerformed
        int num = Integer.valueOf(quantityDropdown.getSelectedItem().toString());
        int listIndx = possibleQuestionList.getSelectedIndex();


        if (inputQuestionArea.getText().contains("?")) {
            addQuestion(inputQuestionArea.getText(), num);
        } else if (listIndx >= 0) {
            addQuestion(_possibleQuestions.get(listIndx), num);
        } else {
            statusLabel.setText("No question selected or typed (rememember the ?)");
            statusLabel.setForeground(Color.RED);
        }
    }//GEN-LAST:event_addQuestionButtonActionPerformed

    private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportButtonActionPerformed
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter("data/newQuestions.txt"));
            Set<String> keys = _questionsAdded.keySet();
            for (String k : keys) {
                bw.write(k + "; " + _questionsAdded.get(k) + "\n");
            }
            bw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_exportButtonActionPerformed

    private void inputQuestionAreaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inputQuestionAreaActionPerformed
        if (inputQuestionArea.getText().contains("?")) {
            addQuestion(inputQuestionArea.getText(), 1);
        } else {
            statusLabel.setText("Please enter a full formed question ending with '?'");
            statusLabel.setForeground(Color.RED);
        }
    }//GEN-LAST:event_inputQuestionAreaActionPerformed

private void datePickerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_datePickerActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_datePickerActionPerformed

private void inputQuestionAreaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_inputQuestionAreaKeyPressed
    //System.out.println("key = " + evt.getKeyCode());
    if (evt.getKeyCode() == KeyEvent.VK_TAB) {
        System.out.println("TAB");
    } else if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
        System.out.println("DOWN");
        int currIndx = possibleQuestionList.getSelectedIndex();
        int listSize = possibleQuestionList.getModel().getSize();
        int newIndx = (currIndx + 1) % listSize;
        System.out.println("curr, listSize, new: " + currIndx + ", "
                + listSize + ", " + newIndx);
        if (listSize > 0) {
            possibleQuestionList.setSelectedValue(
                    _possibleQuestions.get(newIndx),
                    true);
            possibleQuestionList.setSelectionInterval(newIndx, newIndx);
            possibleQuestionList.setSelectedIndex(newIndx);
        }
    } else if (evt.getKeyCode() == KeyEvent.VK_UP) {
        System.out.println("UP");
        int currIndx = possibleQuestionList.getSelectedIndex();
        int listSize = possibleQuestionList.getModel().getSize();
        System.out.println("curr, listSize, new: " + currIndx + ", "
                + listSize + ", " + ((currIndx - 1 + listSize) % listSize));
        if (listSize > 0) {
            if (currIndx < 0) {
                possibleQuestionList.setSelectedIndex(listSize - 1);
            } else {
                possibleQuestionList.setSelectedIndex((currIndx - 1 + listSize) % listSize);
            }
        }
    }


    String query = inputQuestionArea.getText().toLowerCase();
    Vector<String> possibleQuestions = new Vector<String>();

    for (int i = 0; i < _lowerCaseQuestions.size(); ++i) {
        if (_lowerCaseQuestions.get(i).contains(query)) {
            possibleQuestions.add(_allQuestions.get(i));
        }
    }

//        for (String q : _allQuestions) {
//            if (q.contains(query)) {
//                possibleQuestions.add(q);
//            }
//        }

    _possibleQuestions = possibleQuestions;
    possibleQuestionList.setListData(possibleQuestions);
}//GEN-LAST:event_inputQuestionAreaKeyPressed

    public void setUsers(Vector<String> users) {
        userDropdown.removeAllItems();
        for (String u : users) {
            userDropdown.addItem(u);
        }
    }
    
    public void setList(Vector<String> questions) {
        //jList1.setListData(possibleQuestions);
        _possibleQuestions = questions;
        _allQuestions = questions;
        possibleQuestionList.setListData(questions);
        for (String q : questions) {
            _lowerCaseQuestions.add(q.toLowerCase());
        }
    }

    private void resetQuantity() {
        quantityDropdown.setSelectedIndex(0);
    }

    public void addQuestion(String question, int quantity) {


        if (_questionsAdded.containsKey(question)) {
            int count = _questionsAdded.get(question);
            _questionsAdded.put(question, count + quantity);
            System.out.println("updating(" + quantity + "/" + count + ") " + question);
        } else {
            System.out.println("adding(" + quantity + ") " + question);
            _questionsAdded.put(question, quantity);
        }
        System.out.println(userDropdown.getSelectedItem().toString() + " " + datePicker.getDate());

        String msg = " successfully added " + quantity + " question"
                + (quantity == 1 ? "" : "s") + " (" + question + ")";
        statusLabel.setText(msg);
        statusLabel.setForeground(new Color(0F, 0.6F, 0F));
        resetQuantity();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addQuestionButton;
    private javax.swing.JToggleButton bannerButton;
    private org.jdesktop.swingx.JXDatePicker datePicker;
    private javax.swing.JButton exportButton;
    private javax.swing.JTextField inputQuestionArea;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JList possibleQuestionList;
    private javax.swing.JComboBox quantityDropdown;
    private javax.swing.JLabel statusLabel;
    private javax.swing.JComboBox userDropdown;
    // End of variables declaration//GEN-END:variables
}
